package com.leyou.search.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.configuration.OSSProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Service
public class UploadService {

    @Autowired
    private OSSProperties prop;

    @Autowired
    private OSS client;

    //支持的文件类型
    private static final List<String> suffixes = Arrays.asList("image/png","image/jpeg","imag/bmp");

    public String upload(MultipartFile file) {
        /*获取文件类型*/
        String type = file.getContentType();
        /*如果该文件类型不是我们想要的文件类型*/
        if (!suffixes.contains(type)){
            throw new LyException(ExceptionEnum.FILE_TYPE_ERROR);
        }

        /*读取文件*/
        BufferedImage image = null;
        try {
            image = ImageIO.read(file.getInputStream());
        } catch (IOException e) {
            throw new LyException(ExceptionEnum.FILE_READ_ERROR);
        }
        if (image == null){
            throw new LyException(ExceptionEnum.FILE_NOT_NULL);
        }

        /*获取文件保存路径，设置这个路径可以直接通过 nginx 来访问到*/
        File dir = new File("D:\\nginx-1.12.2\\html\\");

        try {
            /*将图片保存到此路径下*/
            file.transferTo(new File(dir,file.getOriginalFilename()));
            System.out.println(file.getOriginalFilename());
            /*返回文件路径*/
            return "http://image.leyou.com//" + file.getOriginalFilename();
        } catch (IOException e) {
            throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR);
        }

    }

    public Map<String, Object> getSignature() {
        try {
            long expireTime = prop.getExpireTime();   //过期时间
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, prop.getMaxFileSize());
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, prop.getDir());
            /*封装 过期时间以及上传策略*/
            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.calculatePostSignature(postPolicy);

            Map<String, Object> respMap = new LinkedHashMap<>();
            respMap.put("accessId", prop.getAccessKeyId());
            respMap.put("policy", encodedPolicy);  //上传策略是自己生成的
            respMap.put("signature", postSignature);  //签名，这个签名将许多参数都合并了，包括 accessKeySecret
            respMap.put("dir", prop.getDir());
            respMap.put("host", prop.getHost());
            respMap.put("expire", expireEndTime);
            return respMap;
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
    }
}
